package com.xiang.handler;

import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.timeout.IdleState;
import io.netty.handler.timeout.IdleStateEvent;
import io.netty.handler.timeout.IdleStateHandler;
import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.TimeUnit;

/**
 *  IdleStateHandler 既是InbandHandler 也是 OutbandHandler
 */
@Slf4j
@ChannelHandler.Sharable
public class ServerIdleHandler extends IdleStateHandler {

    public ServerIdleHandler() {
        // allIdleTime = 6 s未读取到数据
        super(0, 0, 6, TimeUnit.SECONDS);
    }

    @Override
    protected void channelIdle(ChannelHandlerContext ctx, IdleStateEvent evt) throws Exception {
//        6s未读取到数据Idle 触发
        if(evt ==  IdleStateEvent.FIRST_READER_IDLE_STATE_EVENT){
            log.info("ServerIdleHandler 触发FIRST_READER_IDLE_STATE_EVENT事件 ");
            log.info("6s未读取到数据！链接关闭 ");
            ctx.channel().close();
            return;
        }
        if(evt ==  IdleStateEvent.READER_IDLE_STATE_EVENT){
            log.info("ServerIdleHandler 触发READER_IDLE_STATE_EVENT事件 ");

        }
        if(evt ==  IdleStateEvent.FIRST_WRITER_IDLE_STATE_EVENT){
            log.info("ServerIdleHandler 触发FIRST_WRITER_IDLE_STATE_EVENT事件 ");
        }
        if(evt ==  IdleStateEvent.WRITER_IDLE_STATE_EVENT){
            log.info("ServerIdleHandler 触发WRITER_IDLE_STATE_EVENT事件 ");
        }
        if(evt ==  IdleStateEvent.FIRST_ALL_IDLE_STATE_EVENT){
            log.info("ServerIdleHandler 触发FIRST_ALL_IDLE_STATE_EVENT事件 ");
        }
        if(evt ==  IdleStateEvent.ALL_IDLE_STATE_EVENT){
            log.info("ServerIdleHandler 触发ALL_IDLE_STATE_EVENT事件 ");
        }
        super.channelIdle(ctx, evt);
    }

    @Override
      public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception {
              if(evt instanceof IdleStateEvent){
                      if(((IdleStateEvent)evt).state().equals(IdleState.READER_IDLE)){
                          log.info("ServerIdleHandler Read Idle");
                             ctx.close();
                         }
                  }else{
                      super.userEventTriggered(ctx, evt);
                  }
              }

}
